PDF生成、合并及压缩优化(Java)

您所在的位置:网站首页 图像算法优化 java PDF生成、合并及压缩优化(Java)

PDF生成、合并及压缩优化(Java)

2024-07-10 13:38| 来源: 网络整理| 查看: 265

依赖文件:

com.itextpdf itextpdf 5.5.10 com.itextpdf itext-asian 5.2.0

创建PDF文件

public PdfReader getPdfBytes(Element element) { if (element == null) { return null; } Document document = new Document(); try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); PdfWriter writer = PdfWriter.getInstance(document, bos); writer.setFullCompression(); writer.setCompressionLevel(PdfStream.BEST_COMPRESSION); document.open(); document.add(element); document.close(); writer.close(); return new PdfReader(bos.toByteArray()); } catch (Exception e) { logger.error("getPdfBytes error", e); } return null; } public PdfPTable getUserTableInfo(List data) { PdfPTable table = new PdfPTable(3); table.setWidthPercentage(100); float width = PageSize.A4.getWidth() - 40; float dataWidth = width / 4; float[] columnWidth = new float[] { dataWidth, dataWidth, dataWidth * 2}; try { table.setTotalWidth(columnWidth); } catch (Exception e) { table.setTotalWidth(width); } table.addCell(getPdfCellInfo("ID")); table.addCell(getPdfCellInfo("用户")); table.addCell(getPdfCellInfo("简介")); if (CollectionUtils.isNotEmpty(data)) { data.stream().forEach(col -> { table.addCell(getPdfCellInfo(col.getId())); table.addCell(getPdfCellInfo(col.getUserName())); table.addCell(getPdfCellInfo(col.getUserText())); }); } return table; } private PdfPCell getPdfCellInfo(String name) { return getPdfCellInfo(name, 1); } private PdfPCell getPdfCellInfo(String name, int rowSpan) { Font font = getBaseFontInstance(); PdfPCell cell = new PdfPCell(new Paragraph(StringUtils.defaultString(name), font)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); if (rowSpan > 1) { cell.setRowspan(rowSpan); } return cell; } public static Font getBaseFontInstance() { if (baseFont == null) { baseFont = getPdfFont(); } return baseFont; } private static Font getPdfFont() { try { BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); return new Font(bf, 10); } catch (Exception e) { return null; } }

合并pdf

public byte[] createAndMergeBlobPdf(List readers) { if (CollectionUtils.isEmpty(readers)) { return null; } try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); Document document = new Document(); if (CollectionUtils.isNotEmpty(readers)) { PdfCopy copy = new PdfCopy(document, bos); copy.setFullCompression(); copy.setCompressionLevel(PdfStream.BEST_COMPRESSION); document.open(); for (PdfReader reader: readers) { if (reader != null) { int n = reader.getNumberOfPages(); for (int j = 1; j


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3